package com.fuxi;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: Day2
 * @Author: zw
 * @Description: 出百万拳，行万里路；
 * @Create 2025/4/4-23:37
 * @Version 1.0
 */
public class Day2 {
    // 复习多线程
    public static void main(String[] args) {
//        for (int i = 0; i < 100; i++) {}; // 这里由于还没有开启子线程，此时不会有资源争抢
//        Testthread t = new Testthread();
//        t.start(); // 启动了子线程就会和主线程争抢资源
//        // 主线程继续for
//        for (int i = 0; i < 100; i++) {
//            System.out.println("我主线程");
//        };
        SellTicket sellTicket = new SellTicket();
        Thread thread1 = new Thread(sellTicket, "窗口1");
        Thread thread2 = new Thread(sellTicket, "窗口2");
        Thread thread3 = new Thread(sellTicket, "窗口3");
        //start
        thread1.start();
        thread2.start();
        thread3.start();
    }
    public static class Testthread extends Thread {
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println("我是子线程");
            }
        }
    }
    // 售票案例
    public static class SellTicket implements Runnable {
        private int tickets = 100;
//        private Object obj = new Object();
        public  synchronized  void  sealtickfun() {
            this.tickets--;
            System.out.println(Thread.currentThread().getName() + ":" + this.tickets);
        }
        private Lock lock = new ReentrantLock();
        @Override
        public void run() {
//            synchronized (obj) { // 这里必须要要是同一个对象，意味这要是同一把锁
            try {
                lock.lock();
                while (tickets > 0) {
                    // 卖票出票也是需要时间
                    // 通过sleep让当前窗口进行出票，
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    this.tickets--;
                    System.out.println(Thread.currentThread().getName() + ":" + this.tickets);
                }
            } finally {
                lock.unlock();
            }

//            }
        }
    }
}

